package com.spzx.test.t6;

import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Tree {

    Integer apple = 9;

    Lock lock = new ReentrantLock();// 默认是false

    @SneakyThrows
    public void get() {
        //lock.lock();// 等待
        boolean b = lock.tryLock(3,TimeUnit.SECONDS);// 不等待，直接返回false值
        if(b){
            if (apple > 0) {
                try {
                    System.out.println(Thread.currentThread().getName() + "开始摘苹果了");
                    apple--;
                    TimeUnit.SECONDS.sleep(RandomUtils.nextInt(1, 5));
                    System.out.println(Thread.currentThread().getName() + "摘走一颗苹果,剩余苹果数量" + apple);
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "苹果摘完了：" + apple);
            }
        }else {
            System.out.println(Thread.currentThread().getName() + "不排队了，没时间了，我要赶着回家写代码了");
        }

    }

}
